package cn.topcode.controller;

import cn.topcode.beans.dto.Dto;
import cn.topcode.beans.pojo.Question;
import cn.topcode.beans.pojo.User;
import cn.topcode.beans.vo.questionVO.FreeQuestionVO;
import cn.topcode.service.RpcQuestionService;
import cn.topcode.utils.Constants;
import cn.topcode.utils.DtoUtil;
import cn.topcode.utils.ValidationToken;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/question")
public class QuestionController {

    @Reference
    private RpcQuestionService rpcQuestionService;
    @Resource
    private ValidationToken validationToken;

    /***
     * 免费提问
     * @param freeQuestionVO 问题
     * @param request
     * @return
     */
    @ApiOperation(value = "免费提问", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "免费提问 ")
    @RequestMapping(value = "freeAsk", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto freeAsk(@RequestBody FreeQuestionVO freeQuestionVO, HttpServletRequest request) {
        String token = request.getHeader("token");
        User currentUser = validationToken.getCurrentUser(token);
        if (null == currentUser)
            return DtoUtil.returnFail("token失效，请重登录", Constants.User_AUTH.AUTH_TOKEN_INVALID);
        if (null == freeQuestionVO || null == freeQuestionVO.getqContext())
            return DtoUtil.returnFail("问题不能为空", Constants.FreeAsk.QUESTION_IS_NULL);
        try {
            if (rpcQuestionService.addQuestion(freeQuestionVO, currentUser))
                return DtoUtil.returnSuccess("发表成功");
            return DtoUtil.returnFail("发表失败", Constants.FreeAsk.FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), Constants.SYSTEM_ERROR);
        }
    }

    /***
     * 图片上传
     * @param request
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto upload(@RequestParam MultipartFile multipartFile, HttpServletRequest request) {
        List<String> dataList = new ArrayList<String>();
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            int fileCount = 0;
            try {
                fileCount = multiRequest.getFileMap().size();
            } catch (Exception e) {
                fileCount = 0;
                return DtoUtil.returnFail("文件大小超限", "100009");
            }
            if (fileCount > 0 && fileCount <= 4) {
                String tokenString = multiRequest.getHeader("token");
                User currentUser = validationToken.getCurrentUser(tokenString);
                if (null != currentUser) {
                    //取得request中的所有文件名
                    Iterator<String> iterator = multiRequest.getFileNames();
                    while (iterator.hasNext()) {
                        try {
                            //取得上传文件
                            MultipartFile file = multiRequest.getFile(iterator.next());
                            if (file != null) {
                                //取得当前上传文件的文件名称
                                String myFileName = file.getOriginalFilename();
                                //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                                if (myFileName.trim() != ""
                                        &&
                                        (
                                                myFileName.toLowerCase().contains(".jpg")
                                                        || myFileName.toLowerCase().contains(".jpeg")
                                                        || myFileName.toLowerCase().contains(".png")
                                        )) {
                                    //重命名上传后的文件名
                                    //命名规则：用户id+当前时间+随机数
                                    String suffixString = myFileName.substring(file.getOriginalFilename().indexOf("."));
                                    String fileName = currentUser.getUId() + "-" + System.currentTimeMillis() + "-" + ((int) (Math.random() * 10000000)) + suffixString;
                                    //定义上传路径
                                    String path = "D:\\project\\doctorOnline\\upload";
                                    System.out.println(path);
                                    File localFile = new File(path, fileName);
                                    file.transferTo(localFile);
                                    dataList.add(path + fileName);
                                }
                            }
                        } catch (Exception e) {
                            continue;
                        }
                    }
                    return DtoUtil.returnSuccess("文件上传成功", dataList);
                } else {
                    return DtoUtil.returnFail("文件上传失败", "100006");
                }
            } else {
                return DtoUtil.returnFail("上传的文件数不正确，必须是大于1小于等于4", "100007");
            }
        } else {
            return DtoUtil.returnFail("请求的内容不是上传文件的类型", "100008");
        }
    }
}
